   package com.javalong.affairs.base.utils;

import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class FileUtils {
	public static void download(final Button bt, String url, final String path) {
		com.lidroid.xutils.HttpUtils http = new com.lidroid.xutils.HttpUtils();
		http.download(url, path, true, true, new RequestCallBack<File>() {

			public void onStart() {
				bt.setText("正在连接...");
				bt.setClickable(false);
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				bt.setText(current + "/" + total);
				bt.setClickable(false);
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				bt.setText("重新下载");
				bt.setClickable(true);
			}

			@Override
			public void onSuccess(ResponseInfo<File> responseInfo) {
				bt.setText("打开");
				bt.setClickable(true);
				bt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						File file = new File(path);
						if (file.exists() && file.isFile()) {
							FileUtils.openFile(bt.getContext(), file);
						} else {
							ToastUtils.showMessage("文件不存在或已损坏");
						}
					}
				});

			}
		});

	}

	private static void openFile(Context context, File f) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);

		String type = getMIMEType(f);
		intent.setDataAndType(Uri.fromFile(f), type);
		context.startActivity(intent);
	}

	private static String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			type = "audio";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image";
		} else {
			type = "*";
		}
		type += "/*";
		return type;
	}

}
